/*
 * Copyright 2008 Jens Meiss
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License. 
 * You may obtain a copy of the License at 
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.googlecode.hmvc4gwt.framework.client.registry.artifactregistry;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.googlecode.hmvc4gwt.framework.client.registry.artifactregistry.events.in.AddActiveArtifactEvent;
import com.googlecode.hmvc4gwt.framework.client.registry.artifactregistry.events.in.LoadRemoteArtifactsEvent;
import com.googlecode.hmvc4gwt.framework.client.registry.artifactregistry.events.in.RemoveActiveArtifactEvent;
import com.googlecode.hmvc4gwt.framework.client.registry.artifactregistry.events.in.StartArtifactEvent;
import com.googlecode.hmvc4java.component.Component;
import com.googlecode.hmvc4java.component.IComponent;
import com.googlecode.hmvc4java.event.IEvent;
import com.googlecode.hmvc4java.registry.controller.AControllerModelRegistry;
import com.googlecode.hmvc4java.registry.eventregistry.events.in.AddEventRegistryListenerEvent;

/**
 * 
 *
 * @author jens.meiss
 */
public class ArtifactRegistryController extends AControllerModelRegistry<ArtifactRegistryModel> {

	private static ArtifactRegistryController artifactRegistryController;
	
	public static void startArtifactRegistry() {
		
		if (artifactRegistryController == null) {
			artifactRegistryController = new ArtifactRegistryController();
			IComponent component = new Component(new ArtifactRegistryModel(), artifactRegistryController);
			component.initComponent();
		}
		
	}
	
	private ArtifactRegistryController() {
	}
	
	public void init() {
		
		getModel().setMapActiveArtifacts(new HashMap<Class<? extends IArtifact>, IArtifact>(ArtifactRegistryModel.mapActiveArtifacsInitialCapacity));
		
		fireEventGlobal(new AddEventRegistryListenerEvent(AddActiveArtifactEvent.class, this));
		fireEventGlobal(new AddEventRegistryListenerEvent(RemoveActiveArtifactEvent.class, this));
		fireEventGlobal(new AddEventRegistryListenerEvent(LoadRemoteArtifactsEvent.class, this));
		
	}

	public void terminate() {
	}

	public void handleEvent(IEvent event) {
		if (event.getClass() == AddActiveArtifactEvent.class) {
			addActiveArtifact(((AddActiveArtifactEvent) event).getActiveArtifac());
		} else if (event.getClass() == RemoveActiveArtifactEvent.class) {
			removeActiveArtifact(((RemoveActiveArtifactEvent) event).getClassOfArtifact());
		} else if (event.getClass() == LoadRemoteArtifactsEvent.class) {
			loadRemoteArtifacts();
		}
	}

	/**
	 * 
	 */
	private void loadRemoteArtifacts() {
		IArtifactsRemoteAsync async = IArtifactsRemote.Util.getInstance();
		async.getListAvailableArtifactClassNames(new AsyncCallback<List<ArtifactClassname>>() {
			
			public void onFailure(Throwable caught) {
				Window.alert(caught.getMessage());
			};
			
			public void onSuccess(List<ArtifactClassname> listartifacts) {
				startRemoteArtifact(listartifacts);
			}
		});
	}

	private void startRemoteArtifact(List<ArtifactClassname> listArtifacts) {
		
		if (listArtifacts == null) {
			return;
		}
		
		Iterator<ArtifactClassname> iteratorClassnames = listArtifacts.iterator();
		while (iteratorClassnames.hasNext()) {
			
			String classnameOfArtifac = iteratorClassnames.next().getArtifactClassname();
			boolean artifactIsRunning = false;
			
			/*
			 * compare the currently running artifacts with the list of artifacts to start
			 */
			Iterator<Class<? extends IArtifact>> iteratorActiveArtifacts = getModel().getMapActiveArtifacts().keySet().iterator();
			while (iteratorActiveArtifacts.hasNext()) {
				Class<? extends IArtifact> classOfActiveArtifact = (Class<? extends com.googlecode.hmvc4gwt.framework.client.registry.artifactregistry.IArtifact>) iteratorActiveArtifacts
						.next();
				
				if (classOfActiveArtifact.equals(classnameOfArtifac)) {
					/*
					 * artifact is currently running - don't start it again
					 */
					artifactIsRunning = true;
					break;
				}
				
			}
			
			/*
			 * only start the Artifact if it is currently not running
			 */
			if (!artifactIsRunning) {
				fireEventGlobal(new StartArtifactEvent(classnameOfArtifac));
			}
		}
	};
	
	/**
	 * @param classOfArtifact
	 */
	private void removeActiveArtifact(Class<? extends IArtifact> classOfArtifact) {
		getModel().getMapActiveArtifacts().remove(classOfArtifact);
	}

	/**
	 * @param activeArtifac
	 */
	private void addActiveArtifact(IArtifact activeArtifac) {
		
		if (getModel().getMapActiveArtifacts() == null) {
			getModel().setMapActiveArtifacts(new HashMap<Class<? extends IArtifact>, IArtifact>(ArtifactRegistryModel.mapActiveArtifacsInitialCapacity));
		}
		
		getModel().getMapActiveArtifacts().put(activeArtifac.getClass(), activeArtifac);
	}

	public void initModel() {
		// TODO Auto-generated method stub
		
	}

}
